<template>
    <div>
        <el-row :gutter="15">
            <el-col :span="statement.status==0?15:21" :offset="1" class="left">
                <!-- 左上 -->
                <el-row class="left-top">
                    <el-descriptions :column="2">
                        <el-descriptions-item label="客户姓名">{{ statement.customerName }}</el-descriptions-item>
                        <el-descriptions-item label="联系方式">{{ statement.customerPhone}}</el-descriptions-item>
                        <el-descriptions-item label="车牌号码">{{ statement.licensePlate }}</el-descriptions-item>
                        <el-descriptions-item label="汽车类型">{{ statement.carSeries }}</el-descriptions-item>
                        <el-descriptions-item label="服务类型">
                         <dict-tag :options="dict.type.appoint_serv_type" :value="statement.serviceType"/>
                        </el-descriptions-item>
                        <el-descriptions-item label="到店时间">{{ statement.actualArrivalTime }}</el-descriptions-item>
                        <el-descriptions-item label="总消费金额">{{totalSum}}</el-descriptions-item>
                        <el-descriptions-item label="实付价格">{{ payPrice }}</el-descriptions-item>
                        <el-descriptions-item label="优惠价格" v-if="statement.status == 0">
                            <el-input class="discountPricesInput" 
                            size="mini"
                            v-model="statement.discountAmount"
                            @change="changeDiscountPrice">
                            </el-input>
                            </el-descriptions-item>
                        <el-descriptions-item label="优惠价格" v-if="statement.status == 1">
                            {{ statement.discountAmount }}

                         </el-descriptions-item>
 

                    </el-descriptions>
                </el-row>
                <!-- 左下 -->
                <el-row class="left-bottm">
                    <el-col :span="24" >
                        <!-- 按钮 -->
                        <el-row :gutter="10" class="mb8" v-if="statement.status== 0">
                            <el-col :span="1.5">
                                <el-button type="primary"
                                plain icon="el-icon-plus"
                                @click="statementItemSaveHandle"
                                :disabled="saveFlag"
                                size="mini">保存</el-button>
                            </el-col>

                            <el-col :span="1.5">
                                <el-button type="warning"
                                 plain icon="el-icon-money"
                                 @click="payHandle"
                                 :disabled="payFlag"
                                 size="mini">支付</el-button>
                            </el-col>

                        </el-row>
                        <!-- 表格数据 -->
                        <el-table v-loading="loading" :data="statementItemList">
                            <el-table-column label="服务名称" align="center" prop="itemName" />
                            <el-table-column label="服务原价" align="center" prop="itemPrice" />
                            <el-table-column label="服务数量" align="center" prop="itemQuantity" />
                            <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                            v-if="statement.status== 0">
                                <template slot-scope="scope">
                                    <el-button size="small"
                                    type="primary"
                                    icon="el-icon-plus"
                                     @click="itemQuantityAddHandle(scope.$index)">

                                </el-button>
                                    <el-button
                                     size="small"
                                     type="danger"
                                      icon="el-icon-minus"
                                     @click="itemQuantitysubHandle(scope.$index)"> <!-- 传递索引值 -->
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                    <div class="page">
                        显示第 1 到第{{statementItemList.length}}条记,总共{{statementItemList.length}}条记录
                    </div>
                </el-row>
            </el-col>
            <el-col :span="8" calss="right" v-if="statement.status== 0">
                <!-- 右上 -->
                <el-row class="right-top">
                    <el-col :span="24">
                        <el-form :model="queryParams" size="small" :inline="true" label-width="68px">
                            <el-form-item label="服务名称" prop="name">
                                <el-input v-model="queryParams.name" placeholder="请输入服务项名称" clearable
                                    @keyup.enter.native="handleQuery" />
                            </el-form-item>
                            <el-form-item label="是否套餐" prop="carPackage">
                                <el-select v-model="queryParams.carPackage" placeholder="请选择套餐" clearable>
                                    <el-option v-for="dict in dict.type.item_serv_package" :key="dict.value"
                                        :label="dict.label" :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="服务分类" prop="serviceCatalog">
                                <el-select v-model="queryParams.serviceCatalog" placeholder="请选择服务分类" clearable>
                                    <el-option v-for="dict in dict.type.item_serv_type" :key="dict.value"
                                        :label="dict.label" :value="dict.value" />
                                </el-select>
                            </el-form-item>

                            <el-form-item label=" ">
                                <el-button round type="success" icon="el-icon-search" size="medium"
                                    @click="handleQuery">搜索</el-button>

                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
                <!-- 右下 -->
                <el-row class="right-bottom">
                    <el-col :span="24">
                        <!-- 表格数据 -->
                        <el-table v-loading="loading" :data="serviceItemList">
                            <el-table-column label="服务项名称" align="center" prop="name" />
                            <el-table-column label="服务价格" align="center" prop="discountPrice" />
                            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                    size="small"
                                    type="primary"
                                    icon="el-icon-plus"
                                   @click="addStatementItemHandle(scope.row)"
                                   ></el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="page">
                            显示第 1 到第 {{serviceItemList.length}}条记录,总共
                          X条记录
                        </div>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>  
    </div>
</template>

<script>
import { getServiceItemList } from "@/api/business/serviceltem";
import { getStatement } from "@/api/business/statement";
import { statementItemSave,getStatementItemList,pay } from "@/api/business/statementItem";
export default{
    name: 'statementItem',
dicts: ['item_serv_package', 'item_serv_type', 'appoint_serv_type'],
    data() {
        return {

            statementId: this.$route.params.statementId,//结算单Id
            statementItemList: [],//结算单明细列表集合
            serviceItemList: [],//服务列表集合
            statement: {
                 discountAmount: 0,
            },  //结算单对象
            loading: false,  //遮罩层
            saveFlag: true,  //保存按钮是否禁用
            payFlag: true,  //支付按钮是否禁用
            queryParams: {    //高级搜索
                name: null,
                carPackage: null,
                serviceCatalog: null,
                saleStatus: 1          //只要上架状态的数据
            }
        }
    },
    created() {
        this.initData();  //页面数据初始化
    },
    methods:{
        //页面初始化数据方法
        initData(){
        //初始化已上架服务项数据  serviceItemList
        this.getServiceItemListHandler();
        //初始化结算单明细数据  statementItemList
        this.getStatementItemListHandle();
        //初始化结算单数据  statement
        this.getStatementHandle();

        },
        // 查询已上架服务项列表数据
        getServiceItemListHandler(){

            getServiceItemList(this.queryParams).then(resp => {
                this.serviceItemList = resp.data;
                console.log(resp.data);

            });
        },
        //根据结算单id查询列表对象数据 （左上）  getStatement
        getStatementHandle(){
            getStatement(this.statementId).then(resp => {
                this.statement = resp.data;
                console.log(resp.data);
            });
        },
        //查询结算单明列表数据
        getStatementItemListHandle(){
            getStatementItemList(this.statementId).then(resp => {
                 //查询到了数据
                if(resp.data.length!=0){
                    // 保存禁用
                   this.saveFlag=true;

                    // 支付可用
                    this.payFlag=false;
                    
                }
                this.statementItemList = resp.data;

            });

        },
       
        //点击右下角添加按钮后触发结算单明列表数据
          addStatementItemHandle(row){
            //创建一个结算单明细 对象
            let obj = {
               itemName: row.name,
               itemPrice: row.discountPrice,
               itemQuantity:1,
               itemId:row.id,
               statementId: this.statementId
            }
             //判断是否是首次添加，首次则添加，否则执行更新
           let index=  this.getStatementItemIndexByServiceItemId(row.id);
           // console.log("调用方法后返回索引值"+index)
           if(index>=0){
            //找到了，则数量加1
            this.statementItemList[index].itemQuantity++;
           }else{
            //没有找到，则添加
            this.statementItemList.push(obj);
           }
           //更新支付和保存按钮的状态
           //保存禁用
           this.saveFlag=false;
           //支付可用
           this.payFlag=true;
            

        },
        //根据服务项 ID 在结算单明细列表中查找是否存在
        getStatementItemIndexByServiceItemId(id){
          let i = -1;
          //遍历 statementItemList 集合
          this.statementItemList.forEach((statementItem,index) => {
            if(statementItem.itemId == id){
              //找到了 返回对应索引
              console.log("找到的索引: " + index);
              i = index;
              return
            }
          })
          return i;
        },
         //点击左下结算单明细加号按钮
        itemQuantityAddHandle(index){
         this.statementItemList[index].itemQuantity++; // <--- 修改这里
        },
        //点击左下结算单明细减号按钮
        itemQuantitysubHandle(index){
    //判断剩余数量
    if(this.statementItemList[index].itemQuantity <= 1){
         // <--- 修改点：使用 index
        //若数量等于1 则删除元素
        this.statementItemList.splice(index,1);
    }else{
      //数量大于1 则减1
        this.statementItemList[index].itemQuantity--; // <--- 修改点：使用 index
    }  
    
    //若商品没有，优惠价格变0
       if(this.statementItemList.length != 0){
       
        //保存可用
        this.saveFlag=false;
        //支付禁用
        this.payFlag=true;
       }else{
        //保存禁用
        this.saveFlag=true;
        //支付禁用
        this.payFlag=true;
       }
        // <--- 添加点：更新按钮状态
        },
        // 服务项搜索部分
        handleQuery(){
            this.getServiceItemListHandler();
        },
        //保存功能
        statementItemSaveHandle(){
            this.$modal.confirm('确定保存吗？').then(()=> {
                //封装后台传递的参数
                let data={
                    discountPrices: this.statement.discountAmount,
                    statementItemList:this.statementItemList
                }
                //发送ajax请求
                statementItemSave(data).then(()=>{
                    //查询明细列表
                    this.$modal.msgSuccess("保存成功");
                    ///重新查询结算单数据
                    this.getStatementHandle();
                   //修改保存支付按钮的状态
                   //保存可用
                   this.saveFlag=false;
                   //支付可用
                   this.payFlag=true;
                })


            }) 
            
        },
        //验证输入的折扣价
        changeDiscountPrice(){
    // 验证 折扣价 > 总价格  ||  折扣价 < 0   ||  折扣价是非数字
       if(this.statement.discountAmount > this.totalSum || this.statement.discountAmount < 0
       || isNaN(this.statement.discountAmount)){
        this.$alert("当前输入格式有错误", {
            confirmButtonText: "确定",
            callback: (action) => {
                this.statement.discountAmount = 0;
            }
        });
    }
    //保存可用
    this.saveFlag=false;
    //支付禁用
    this.payFlag=true;
        },
        //支付按钮
        payHandle(){  
        this.$modal.confirm('确定支付吗？').then(()=> { 
            pay(this.statementId).then(()=>{
                this.$modal.msgSuccess("支付成功");
                //更新结算单状态 从消费中变成已支付 页面会根据状态去改变
                this.getStatementHandle();
                //将保存和支付都禁用 因为 支付了 之后 就不能保存了
                //保存禁用
                this.saveFlag=true;
                //支付禁用
                this.payFlag=true;
             })
            })

        },
    
    },
    computed:{
        // 计算总金额
        totalSum() {
            let sum = 0;
            this.statementItemList.forEach(ele => {
                sum += ele.itemPrice * ele.itemQuantity
            })
            return sum;
        },

      //计算实付价格
payPrice(){
let data = 0;

// 验证折扣金额不能为负数
if(this.statement.discountAmount < 0){
    return 0;
}

// 计算实付金额
data = this.totalSum - this.statement.discountAmount;

// 验证实付金额不能为负数
if(data < 0){
    data = 0;
}

// 验证折扣金额不能超过总金额（实付金额不能超过总金额）
if(this.statement.discountAmount > this.totalSum){
    data = this.totalSum;
}

// 验证是否非数字
if(isNaN(data)){
    data = this.totalSum;
}

return data;
}

         // return isNaN(this.totalSum - this.statement.discountAmount <0 ?
         // 0:(this.totalSum - this.statement.discountAmount>this.totalSum ?
         // this.totalSum : this.totalSum-this.statement.discountAmount))?
         // 0 :this.totalSum - this.statement.discountAmount<0?
         // 0:(this.totalSum - this.statement.discountAmount>this.totalSum ?
         // this.totalSum : this.totalSum-this.statement.discountAmount);
    }

}



</script>

<style>
.left-top {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 4px;
    padding: 3% 6%;
    margin-top: 3%;
}

.discountPricesInput {
    width: 30%;
}

.left-bottm {
    margin-top: 2%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 4px;
    padding: 3% 2%;
}

.page {
    line-height: 34px;
    font-size: 13px;
    color: #676a6c;
}

.right-top {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 4px;
    padding: 3% 6%;
    margin-right: 6%;
    margin-top: 6%;
}

.right-bottom {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 4px;
    padding: 4% 6%;
    margin: 5% 5% 0% 0%;
}

</style>
